import React, { Component} from 'react';
import { View, StyleSheet ,Dimensions, Platform} from 'react-native';

import PropTypes from "prop-types";
import Radio from './Radio';
import CheckBox from './CheckBox';
import Color from '../../config/theme/standard/color';

export default class BlockSelect extends Component{
    constructor(props) {
        super(props);
        let checkedArr = [];
        let disabledArr = [];
        if(this.props.type == 'checkbox'){
            this.props.data.map((item, index) => {
                if(item.checked){
                    checkedArr.push(index+1);
                }
            });
        }
        this.state = {
            prevPropsIndex: props.defaultIndex,
            index: props.defaultIndex,
            data: props.data,
            checkedArr: checkedArr,
            disabledArr: disabledArr,
            isWideScreen: false // 鸿蒙适配是否宽屏
        };
    };

    componentDidMount() {
        // 适配鸿蒙折叠屏动态更新组件
        this.addEventListenerScreenWidth = Dimensions.addEventListener('change', this.setIsWideScreen)
    }

    componentWillUnmount(){
        // 适配鸿蒙折叠屏动态更新组件
        if (this.addEventListenerScreenWidth) {
            this.addEventListenerScreenWidth = null
        }
    }

    setIsWideScreen = () => {
        const screenWidth = Dimensions.get('window').width;
        if (screenWidth) {
            this.setState({
                isWideScreen: screenWidth > 500 && screenWidth < 800
            })
        }
    }


    static getDerivedStateFromProps(nextProps, prevState) {
        if (('defaultIndex' in nextProps) && (nextProps.defaultIndex !== prevState.prevPropsIndex)) {
            return {
                prevPropsIndex: nextProps.defaultIndex,
                index: nextProps.defaultIndex
            };
        }
        return null;
    }

    _createItem (){
        if (this.props.type == 'radio') {
            return this._radioItem();
        } else if (this.props.type == 'checkbox') {
            return this._checkBoxItem();
        }
    }

    _radioItem(){

        let radioItem;

        radioItem = <View style={{width:'100%'}}>
            <Radio
                initial={this.state.index}
                radio_props={this.props.data}
                size={this.props.size}
                style={this.props.style}
                isRadius={this.props.isRadius}
                selectedColor={this.props.selectedColor}
                unSelectedColorText={this.props.unSelectedColorText}
                unSelectedColorBorder={this.props.unSelectedColorBorder}
                borderRadius={this.props.borderRadius}
                onPress={(index) => this._onPress(index)}
            />
        </View>;

        return radioItem;

    }

    _checkBoxItem(){
        const checkboxStyle = [styles.checkBox];
        let marginLeft;
        let columnCount;

        switch (this.props.size) {
            case 'large':
                columnCount = 3;
                marginLeft = 19;
                break;
            case 'middle':
                columnCount = 4;
                marginLeft = 11;
                checkboxStyle.push({marginVertical: 9});
                break;
            case 'small':
                columnCount = 5;
                marginLeft = 12;
                checkboxStyle.push({marginVertical: 5});
                break;
            case 'self':
                marginLeft = 0;
                checkboxStyle.push({marginVertical: 9});
                break;
        }

        if(this.state.data.length == 0) {
            return false;
        }

        let arr = this.state.data;

        return arr.map((item, i) => {
            return (
                <View style={[[{marginVertical: item.description ? 10 : 5}, checkboxStyle], {marginLeft: i % columnCount == 0 ? 0 : marginLeft, marginRight: this.props.size == 'self' ? 12 : 0}]} key={i}>
                    <CheckBox
                        label = {item.label}
                        description = {item.description}
                        number = {i+1}
                        value = {item.value}
                        isChecked = {item.checked}
                        disabled = {item.disabled ? item.disabled : this.state.checkedArr.length == this.props.maxSelectedOptions? i+1 == this.state.disabledArr[i] ? false : true : false}
                        style = {this.props.style}
                        isRadius = {this.props.isRadius}
                        size = {this.props.size}
                        selectedColor={this.props.selectedColor}
                        unSelectedColorText={this.props.unSelectedColorText}
                        unSelectedColorBorder={this.props.unSelectedColorBorder}
                        borderRadius={this.props.borderRadius}
                        onChange = {(checked, number) => this._onCheckBoxChange(checked, number)}
                    />
                </View>
            )
        })
    }

    sortNumber(a,b)
    {
        return a - b
    }

    _onPress(index){
        this.setState({
            index: index
        });

        if(typeof this.props.onPress == 'function'){
            this.props.onPress(index);
        }
    }

    _onCheckBoxChange(checked, number) {
        let tmpArr = this.state.checkedArr;
        let arr = this.state.disabledArr;
        let j = 0;
        let add = true, remove = true, index = null;
        for (let i = 0; i < tmpArr.length; i++) {
            if (tmpArr[i] == number && !checked) {
                index = i;
                break;
            }
        }
        if (add && checked) tmpArr.push(number);
        if (remove && !checked) tmpArr.splice(index, 1);
        tmpArr = tmpArr.sort(this.sortNumber);
        for (let i = 0; i < this.state.data.length; i++) {
            if (tmpArr[j] != i+1){
                arr[i] = 0;
            } else {
                arr[i] = tmpArr[j];
                j++;
            }
        }

        if(typeof this.props.onPress == 'function'){
            this.props.onPress(this.state.checkedArr);
        }

        this.setState({
            checkedArr : tmpArr,
            disabledArr: arr,
        });
    }


    render() {
        const containStyle = [styles.container];

        switch (this.props.size) {
            case 'large':
                break;
            case 'middle':
                containStyle.push({paddingHorizontal: Platform.OS == 'harmony' ? 20.8 : 21});
                break;
            case 'small':
                containStyle.push({paddingHorizontal: 0.12 * Dimensions.get('window').width});
                break;
            case 'self':
                containStyle.push({paddingHorizontal: 21});
                break;
        }

        return (
            <View style={containStyle}>
                {this._createItem()}
            </View>
        )
    };
};
BlockSelect.propTypes = {
    // 数据
    data: PropTypes.array,
    // 单选：默认选中项
    defaultIndex: PropTypes.number,
    // 多选：最多可选中数量
    maxSelectedOptions: PropTypes.number,
    // 选择类型：单选/多选
    type: PropTypes.oneOf(['radio','checkbox']),
    // 样式：实心/描边
    style: PropTypes.oneOf(['primary','ghost']),
    // 尺寸： 大/中/小
    size: PropTypes.oneOf(['small', 'middle', 'large','self']),
    // 是否圆角
    isRadius: PropTypes.bool,
    // 选中颜色
    selectedColor: PropTypes.string,
    // 未选中文字颜色
    unSelectedColorText: PropTypes.string,
    // 未选中边框颜色
    unSelectedColorBorder: PropTypes.string,
     // 圆角大小
     borderRadius: PropTypes.number,
};

BlockSelect.defaultProps = {
    // 数据
    data: [],
    // 单选：默认选中项，第一项
    defaultIndex: 0,
    // 多选：最多可选中数量，两个
    maxSelectedOptions: null,
    // 选择类型：单选
    type: 'radio',
    // 样式：描边
    style: 'ghost',
    // 尺寸： 大
    size: 'large',
    // 圆角
    isRadius: true,
    // 选中颜色
    selectedColor: Color.blockSelect.select,
    // 未选中文字颜色
    unSelectedColorText: Color.blockSelect.normalText,
    // 未选中边框颜色
    unSelectedColorBorder: Color.blockSelect.normalBorder,
    // 圆角大小
    borderRadius: 3,

};

const styles = StyleSheet.create({
    container: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        paddingHorizontal: 19,
    },
    checkBox:{
       // marginVertical: 10,
    },
});